package ps.yj.y1j0.data.database;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;
import java.sql.*;

/**
 * @author yanjun
 */
public class YJDataSource {

    private static YJDataSource yjDataSource = null;

    private DataSource dataSource = null;
    private Connection connection = null;

    private YJDataSource() {
        initDataSource();
    }

    public synchronized static YJDataSource getInstance() {
        if (yjDataSource == null)
            yjDataSource = new YJDataSource();
        return yjDataSource;
    }

    private void initDataSource() {
        try {
            Context initContext = new InitialContext();
            Context envContext = (Context) initContext.lookup("java:/comp/env");
            dataSource = (DataSource) envContext.lookup("jdbc/y1j0");
            if (dataSource == null) {
                throw new RuntimeException("不能找到数据源：" + "java:/comp/env/jdbc/y1j0");
            }
        } catch (NamingException e) {
            throw new RuntimeException("不能找到数据源：" + "java:/comp/env/jdbc/y1j0", e);
        }
    }

    /**
     * close the connection of database
     */
    public void closeConnection() {
        if (connection != null)
            try {
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
    }

    public Connection createConnection() throws SQLException {
        if (dataSource != null)
            return dataSource.getConnection();
        return null;
    }
}
